<script lang="ts" setup>
import type { Ref } from 'vue'
import { newApi } from '@/request/api'
import { useHideLoading, useLoading, useNavBack, useRouteGuard, useToast } from '@/utils'
import { onLoad } from '@dcloudio/uni-app'
import { to } from 'await-to-js'
import { ref } from 'vue'
import { object as zobject, string as zstring } from 'zod'

const oid = ref() as Ref<number>
const waybillNo = ref('')
const express = ref('')
const content = ref('')

onLoad(async (query) => {
  const zparse = zobject({
    oid: zstring().regex(/^\d+$/).transform(Number),
  }).safeParse(query)
  if (!zparse.success) {
    return await useRouteGuard()
  }
  oid.value = zparse.data.oid
})

async function handleSubmit() {
  const zparse = zobject({
    number: zstring().min(1, { message: '请填写运单号' }).trim(),
    company: zstring().min(1, { message: '请填写快递公司' }).trim(),
    cont: zstring().trim().optional(),
  }).safeParse({
    number: waybillNo.value,
    company: express.value,
    cont: content.value,
  })
  if (!zparse.success) {
    return useToast(zparse.error.issues[0].message)
  }

  useLoading(true)
  const [err] = await to(newApi.applyForReturn({
    ...zparse.data,
    oid: oid.value,
  }))
  useHideLoading()
  if (err) {
    return
  }

  useToast('提交成功', { icon: 'success' })
  useNavBack()
}
</script>

<template>
  <view class="px-30px pt-20px">
    <!--  -->
    <view class="rd-16px bg-white px-20px">
      <view class="flex items-center px-10px">
        <view class="text-24px text-#3 lh-90px form-item-important-mark">运单号</view>
        <input v-model="waybillNo" type="text" class="h-90px flex-1 text-right text-24px lh-90px" placeholder="请填写(必填)">
      </view>
      <view class="flex items-center b-t-1px b-t-#e0 b-t-solid px-10px">
        <view class="text-24px text-#3 lh-90px form-item-important-mark">快递公司</view>
        <input v-model="express" type="text" class="h-90px flex-1 text-right text-24px lh-90px" placeholder="请填写(必填)">
      </view>
    </view>
    <!--  -->
    <view class="mt-10px rd-16px bg-white px-20px pb-20px">
      <view class="pl-10px text-28px text-#3 lh-70px">描述</view>
      <view class="h-300px rd-16px bg-#F4F5F9 p-15px">
        <textarea v-model="content" class="h-full text-28px" placeholder="请填写"></textarea>
      </view>
    </view>
  </view>

  <view class="fixed bottom-0 w-full flex bg-white pt-15px safe-pb-15px">
    <view class="btn-primary-black mx-a w-600px text-36px lh-80px" @click="handleSubmit">提交</view>
  </view>
</template>

<style lang="less" scoped></style>
